﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using StoragePeriod.Data;
using StoragePeriod.Common;
using StoragePeriod.Model.RawDict;
using StoragePeriod.BLL.RawDict;

namespace StoragePeriod.Web.UserControls
{
    public partial class MaterialTree : System.Web.UI.UserControl
    {
        T_RawMaterial tRawMaterial = new T_RawMaterial(); //原料操作

        #region 属性
        public delegate void TreeEventDelegate(Dictionary<string, string> selectedDic);
        public event TreeEventDelegate SelectedChanging;
        public string Type { get; set; }
        public string BackOrgValue
        {
            get
            {
                if (!Request["BackOrg"].IsNullOrEmpty() && Request["BackOrg"] != "undefined")
                {
                    return Request["BackOrg"];

                }
                return string.Empty;
            }
        }
        private int _rawTypeId = 1;
        public int RawTypeId
        {
            get { return _rawTypeId; }
            set { _rawTypeId = value; }
        }
        public string SelectNode { get; set; }
        public int ExpandLevel { get; set; }
        public string Search { get; set; }
        public string RootPath { get; set; }
        public bool NoPost { get; set; }
        public bool NoBind { get { return RootPath == "NOBIND"; } }
        private int _SelectType = 0;//0为全部 1为：原料
        public int SelectType
        {

            get { return this._SelectType; }
            set { this._SelectType = value; }
        }
        public bool SingleSelect { get; set; }
        public string CurrentSelectOrgCode
        {
            get
            {
                if (SysTree.SelectedNode != null)
                {
                    return SysTree.SelectedNode.Value;
                }
                return string.Empty;
            }
        }
        #endregion

        #region 继承
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
        }
        #endregion

        #region 功能函数

        private void SetClientSelectedOrgValue(string str)
        {
            treeViewSelectValue.Value = String.Format("{0}-{1}", SysTree.SelectedNode.Value, SysTree.SelectedNode.Text);
        }
        private TreeNode GetRawByTypeId(TreeNode tn)
        {
            int Pid = int.Parse(tn.Value);
            List<RawMaterialType> RawTypeList = RawMaterialType.Where("ParentId=@0", Pid).ToList();
            RawTypeList.ForEach(p =>
            {
                TreeNode childNode = new TreeNode()
                {
                    Text = p.TypeName,
                    Value = p.id.ToString(),
                    Target = "0",
                    ShowCheckBox = !SingleSelect
                };
                childNode = GetRawByTypeId(childNode);
                tn.ChildNodes.Add(childNode);
            });

            int TypeId = int.Parse(tn.Value);

            List<E_RawMaterial> rmlist = new List<E_RawMaterial>();
            E_RawMaterial eRawMaterial = new E_RawMaterial();
            switch (this.RawTypeId)
            { 
                case 1:
                    eRawMaterial.StrWhere = string.Format("PeriodTypeID ={0}", TypeId);//食品检测
                    break;
                case 2:
                    eRawMaterial.StrWhere = string.Format("PeriodTypeStorageID ={0}", TypeId); //贮存期预测
                    break;
                case 3:
                    eRawMaterial.StrWhere = string.Format("PeriodTypeKnowledgeID ={0}", TypeId);//营养知识
                    break;
                case 4:
                    eRawMaterial.StrWhere = string.Format("PeriodTypeStorKnowledgeID ={0}", TypeId);
                    break;
            }
            rmlist = tRawMaterial.GetRawListByWhere(eRawMaterial);
            if (rmlist != null)
            {
                rmlist.ForEach(a =>
                {
                    tn.ChildNodes.Add(new TreeNode()
                    {
                        Text = a.RAWName,
                        Value = a.id.EToString(),
                        Target = "1",
                        ShowCheckBox = !SingleSelect
                    });
                });
            }
            return tn;
        }

        public void BindTreeView()
        {
            SysTree.Nodes.Clear();
            List<RawMaterialType> RawTypeList = RawMaterialType.Where("ParentId=@0 and Typeinfoid=@1", 0, Convert.ToInt32(EnumData.TypeInfo.食品检测)).ToList();
            RawTypeList.ForEach(p =>
            {
                TreeNode childNode = new TreeNode()
                {
                    Text = p.TypeName,
                    Value = p.id.EToString(),
                    Target = "0",
                    ShowCheckBox = !SingleSelect
                };
                childNode = GetRawByTypeId(childNode);
                SysTree.Nodes.Add(childNode);
            });
            this.SysTree.CollapseAll();
            if (SysTree.Nodes.Count > 0)
            {
                SysTree.Nodes[0].Select();
                treeViewSelectValue.Value = String.Format("{0}-{1}", SysTree.SelectedNode.Value, SysTree.SelectedNode.Text);
            }
        }

        private string LoadRootPathFromBackOrgCode(string BackOrgValue)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取节点类型
        /// </summary>
        private string GetNodeOrgType(string p)
        {
            return p.Split('-').Length > 1 ? p.Split('-')[1] : string.Empty;
        }

        #endregion

        #region 事件

        protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this.btSure, this.GetType(), "alert", "<script>$(document).ready(function () { TreeRadioOrMulti();});</script>", false);

            if (IsPostBack) return;
            BindTreeView();

            if (!BackOrgValue.IsNullOrEmpty())
            {
                TreeNode tn = FindNode(SysTree.Nodes, BackOrgValue);
                if (tn == null) return;

                ExpandParentNode(tn);
                tn.Select();
                SetClientSelectedOrgValue(BackOrgValue);
            }
            this.SysTree.Attributes.Add("onclick", "CheckEvent()");
        }

        /// <summary>
        /// 展开父级节点
        /// </summary>
        private void ExpandParentNode(TreeNode tn)
        {
            if (tn == null)
                return;

            if (!tn.Expanded.GetValueOrDefault())
                tn.Expand();

            ExpandParentNode(tn.Parent);
        }

        public TreeNode FindNode(TreeNodeCollection tns, string val)
        {
            return tns.AllNodes().Where(tn => tn.Value == val).FirstOrDefault();
        }

        protected void SysTree_SelectedNodeChanged(object sender, EventArgs e)
        {
            SetClientSelectedOrgValue(SysTree.SelectedNode.Value);
            if (SelectedChanging != null)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                TreeNode tn = SysTree.SelectedNode;
                if (tn.Target != "1") return;
                dic.Add(tn.Value, tn.Text); 
                SelectedChanging(dic);
            }
        }

        #endregion

        protected void btSure_Click(object sender, EventArgs e)
        {
            if (SelectedChanging != null)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                var checkedNodes = SysTree.CheckedNodes;
                foreach (TreeNode tn in checkedNodes)
                {
                    if (_SelectType == 1 || tn.Target == "0") continue;
                    if (!dic.ContainsKey(tn.Value))
                    {
                        dic.Add(tn.Value, tn.Text);
                    }
                }
                SelectedChanging(dic);
            }
        }

        public Dictionary<string, string> GetCheckedNodes()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            SysTree.CheckedNodes.AllNodes().Where(p => p.Target == "1").ToList().ForEach(p =>
            {
                if (!dic.ContainsKey(p.Value))
                {
                    dic.Add(p.Value, p.Text);
                }
            });
            return dic;
        }

    }


}